package rahmath.sharif.docrypt;

import rahmath.sharif.docrypt.constant.DocryptConstants;
import rahmath.sharif.docrypt.entity.Vault;
import rahmath.sharif.docrypt.util.AESCryptor;
import rahmath.sharif.docrypt.util.DocryptUtil;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class CreateVaultActivity extends Activity implements DocryptConstants {

	@TargetApi(11)
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_create_vault);
		if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_create_vault, menu);
		return true;
	}

	public void createVault(View view) {
		String vaultName = ((EditText) findViewById(R.id.editTextVaultName))
				.getText().toString();
		String vaultPassword = ((EditText) findViewById(R.id.editTextVaultPassword))
				.getText().toString();
		String vaultConfirmPassword = ((EditText) findViewById(R.id.editTextVaultConfirmPassword))
				.getText().toString();
		if (0 == vaultName.trim().length()) {
			Toast.makeText(getApplicationContext(),
					getString(R.string.enterVaultName), Toast.LENGTH_SHORT)
					.show();
			return;
		}
		if (0 == vaultPassword.trim().length()
				|| 0 == vaultConfirmPassword.trim().length()) {
			Toast.makeText(getApplicationContext(),
					getString(R.string.enterVaultPassword), Toast.LENGTH_SHORT)
					.show();
			return;
		}
		if (!vaultConfirmPassword.equals(vaultPassword)) {
			Toast.makeText(getApplicationContext(),
					getString(R.string.passwordsNotMatch), Toast.LENGTH_SHORT)
					.show();
			return;
		}
		Vault vault = new Vault(vaultName);
		vault.setPassword(AESCryptor.encryptPassword(256, vaultPassword));
		boolean success = DocryptUtil.putVaultToSD(vault);
		if (success) {
			Toast.makeText(getApplicationContext(),
					getString(R.string.vaultCreatedSuccessfully),
					Toast.LENGTH_SHORT).show();
			finish();
		} else {
			Toast.makeText(getApplicationContext(),
					getString(R.string.vaultNotCreated), Toast.LENGTH_SHORT)
					.show();
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			NavUtils.navigateUpFromSameTask(this);
			return true;
		case R.id.help:
			Intent helpActivity = new Intent(this, HelpActivity.class);
			startActivity(helpActivity);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

}
